package com.itchen.hospital.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itchen.hospital.exception.CustomException;
import com.itchen.hospital.mapper.*;

import java.util.Objects;
import com.itchen.hospital.pojo.*;
import com.itchen.hospital.service.AppointmentService;
import com.itchen.hospital.service.DoctorService;
import com.itchen.hospital.service.SchedulingService;
import com.itchen.hospital.utils.JwtTokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Service
public class AppointmentServiceImpl implements AppointmentService {

    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private SchedulingMapper schedulingMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private UserMapper userMapper;

    //条件查询
    @Override
    public PageInfo<Doctor> search(Params params) {
        //添加一个星期几的查询条件
        String todayWeek = getTodayWeek();
        params.setWeek(todayWeek);
        //处理分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Doctor> list = appointmentMapper.findBySearch(params);
        return PageInfo.of(list);
    }

    /**
     * 从系统时间获取到今天是星期几
     */
    private String getTodayWeek() {

        LocalDate now = LocalDate.now();
        DayOfWeek dayOfWeek = now.getDayOfWeek();
        return dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, java.util.Locale.CHINA);
    }


    /**
     * 挂号
     */

    @Override
    @Transactional
    public void update(Params params) throws ParseException {
        Integer id = params.getId();

        //查询医生信息
        Doctor doctor = doctorMapper.findById(id);

        //再通过医生id查询排班信息
         String todayWeek = getTodayWeek();
        // 输出：星期几（中文）: 星期三
        Date date = params.getTime();
        SimpleDateFormat dfs = new SimpleDateFormat("EEEE", Locale.CHINA);
        String weekDay = dfs.format(date);

        //String appointmentTime = params.getWeek();
        Scheduling scheduling = schedulingMapper.findByDoctorId(doctor.getId(), weekDay);
        if (scheduling == null) {
            throw new CustomException("该医生今日无排班");
        }

        //判断是否还有号
        if (scheduling.getNum() == 0) {
            throw new CustomException("该医生今日已无号");
        }

        //从请求头中获取当前用户
        Admin currentUser = JwtTokenUtils.getCurrentUser();
        User user = new User();

        if (currentUser != null) {
            BeanUtils.copyProperties(currentUser, user);
            user = userMapper.getUserById(user.getId());
        }

        //判断当前用户余额是否充足
        if (user.getPrice() == null) {
            throw new CustomException("用户余额信息缺失");
        }
        if (doctor.getFee() == null) {
            throw new CustomException("医生费用信息缺失");
        }

        int result = user.getPrice().compareTo(doctor.getFee());
        if (result < 0) {
            throw new CustomException(String.format("余额不足, 当前余额: %s, 所需费用: %s",
                     user.getPrice(), doctor.getFee()));
        }

        //将挂号信息存入挂号表
        Patient patient = Patient.builder()
                .DoctorName(doctor.getUsername())
                .PatientName(currentUser.getUsername())
                .build();
        //将前端传来的预约时间，转换格式 前端传的格式为CTS
        if (params.getTime() == null) {
            throw new CustomException("请选择预约时间");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        Date parse = dateFormat.parse(params.getTime().toString());

        //判断预约时间是否早于当前时间
        Date now = new Date();
        if (parse.before(now)) {
            throw new CustomException("预约时间不能早于当前时间");
        }
        String time = sdf.format(parse);
        patient.setAppointmentTime(time);

        //扣除用户的余额
        user.setPrice(user.getPrice().subtract(doctor.getFee()));

        //状态默认为待叫号
        patient.setStatus("-1");
        patientMapper.add(patient);

        //再修改就诊数量
        scheduling.setNum(scheduling.getNum() - 1);
        schedulingMapper.update(scheduling);

    }
}
